package com.jy.wms.controller;

import com.joyi.gate.comm.SessionInfo;
import com.joyi.gate.safety.vo.UserInfo;
import com.jy.wms.common.SetStatus;
import com.jy.wms.common.base.*;
import com.jy.wms.pojo.*;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.jy.wms.service.WmsArtificialReplenishmentService;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.github.pagehelper.Page;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.jy.wms.common.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @ClassName: WmsArtificialReplenishmentController
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @Author LH
 * @Date Mon Nov 27 17:18:31 GMT+08:00 2017
 */

@RestController
@RequestMapping("/wmsartificialreplenishment")
@Api(value = "/wmsartificialreplenishment", description = "关于人工驱动补货操作")
public class WmsArtificialReplenishmentController extends BaseController<WmsArtificialReplenishmentService, WmsArtificialReplenishment> {

    @PostMapping(value = "/list")
    @ApiOperation(value = "查询信息", response = JSONObject.class, notes = "查询信息")
    public @ResponseBody
    JSONObject getWmsArtificialReplenishment(@RequestBody WmsArtificialReplenishment entity, HttpSession session) {
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);//用户信息
        String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库id
        Page<WmsArtificialReplenishment> list = baseService.baseSelectPage(entity, ckid);
        return SetStatus.setSearchType(JSONArray.fromObject(list).toString(), (int) list.getTotal());
    }

    @PostMapping(value = "/getOwner")
    @ApiOperation(value = "查询货主信息", response = JSONObject.class, notes = "查询货主信息")
    public @ResponseBody
    WmsOwner getOwner( HttpSession session) {
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);//用户信息
        String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库id

        String hzid = null;
        List<SysHz> hz = (List) session.getAttribute(BaseSessionInfo.SessionConsignor);//货主
        if (hz.size() > 0) {
            hzid = hz.get(0).getHzid();
        }
        WmsOwner wmsOwner=baseService.getOwner(hzid);

        return wmsOwner;
    }


    @ApiOperation(value = "获取库存信息", response = JSONObject.class, notes = "查询输入</br>{\"hpmc\":\"货品名称模糊查询\",\"hpbh\":\"货品编号模糊查询\"，\"page\":\"页\"，\"rows\":\"行\"}")
    @PostMapping(value = "/getGoods")
    public
    @ResponseBody
    JSONObject getGoods(HttpSession session, @RequestBody Map map) {

        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);//用户信息
        String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库id
        String hzid = null;
        List<SysHz> hz = (List) session.getAttribute(BaseSessionInfo.SessionConsignor);//货主
        if (hz.size() > 0) {
            hzid = hz.get(0).getHzid();
        }
        Page<WmsArtificialReplenishment> list = null;
        try {
            list = baseService.getGoods((String) map.get("hpmc"), (String) map.get("hpbh"), ckid, hzid, (Integer) map.get("page"), (Integer) map.get("rows"));
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return SetStatus.setSearchType(JSONArray.fromObject(list).toString(), (int) list.getTotal());

    }

    /**
     * 获取补货编号
     *
     * @return
     */

    @GetMapping(value = "getBhbh")
    @ApiOperation(value = "获取补货编号", response = JSONObject.class, notes = "获取补货编号")
    public String getBhbh() {
        String bhbh = baseService.getBhbh();//获取补货编号
        return bhbh;
    }

    @PostMapping(value = "add")
    @ApiOperation(value = "新增信息", response = JSONObject.class, notes = "新增信息")
    public @ResponseBody
    JSONObject addWmsArtificialReplenishment(HttpSession session, @RequestBody WmsArtificialReplenishment entity) {
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库id
        List<SysHz> hz = (List) session.getAttribute(BaseSessionInfo.SessionConsignor);
        String hzid = null;
        if (hz.size() > 0) {
            hzid = hz.get(0).getHzid();
        }
        try {
            baseService.baseInsertSelective(entity, userinfo, ckid, hzid);
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "补货单增加成功", "", JSONObject.fromObject(entity).toString());

        } catch (SucessException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "补货单增加成功", "", JSONObject.fromObject(entity).toString());
        } catch (ServiceException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "补货单增加失败", e.getMessage(), "");
        } catch (Exception e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "补货单增加失败", e.getMessage(), "");
        }
    }


    @PostMapping(value = "delete")
    @ApiOperation(value = "删除补货单", response = JSONObject.class, notes = "删除补货单（修改状态，更改为作废）,ids:选中的多条补货单的id集合")
    public @ResponseBody
    JSONObject deleteWmsArtificialReplenishment(HttpSession session, @RequestBody SetAndModifyModel setModel) {
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        try {
            Integer flag = baseService.baseDeleteBathPrimaryKeys(setModel.getIds(), userinfo);
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "补货单删除成功", "", "");

        } catch (SucessException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "补货单删除成功", "", "");

        } catch (ServiceException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "补货单删除失败", e.getMessage(), "");

        } catch (Exception e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "补货单删除失败", e.getMessage(), "");

        }

    }

    @PostMapping(value = "edit")
    @ApiOperation(value = "编辑信息", response = JSONObject.class, notes = "编辑补货单")
    public @ResponseBody
    JSONObject editWmsArtificialReplenishment(HttpSession session, @RequestBody WmsArtificialReplenishment entity) {
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        try {
            baseService.baseUpdateByPrimaryKey(entity, userinfo);
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "补货单编辑成功", "", "");
        } catch (ServiceException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "补货单编辑失败", e.getMessage(), "");

        } catch (SucessException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "补货单编辑成功", "", "");

        } catch (Exception e) {
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "补货单编辑失败", e.getMessage(), "");

        }
    }

    @ApiOperation(value = "编辑时查找明细集合", response = JSONObject.class, notes = "编辑时查找明细集合,ids:补货单id")
    @PostMapping(value = "getDetailList")
    public @ResponseBody
    JSONArray getDetailList(@RequestBody SetAndModifyModel setModel) {
        JSONArray jsonArray = null;
        try {
            jsonArray = baseService.getDetailList(setModel.getIds());
        } catch (ServiceException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonArray;
    }


    @PostMapping(value = "generateReplenishment")
    @ApiOperation(value = "生成补货单", response = JSONObject.class, notes = "生成补货单,ids:选中的多条补货单的id集合")
    public @ResponseBody
    JSONObject generateReplenishment(@RequestBody SetAndModifyModel setModel, HttpSession session) {
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库id
        List<SysHz> hz = (List) session.getAttribute(BaseSessionInfo.SessionConsignor);
        List<SysGys> gys = (List) session.getAttribute(BaseSessionInfo.SessionGys);//供应商
        String hzid = null;
        if (hz.size() > 0) {
            hzid = hz.get(0).getHzid();
        }
        try {
            baseService.generateReplenishment(setModel.getIds(), hzid, userinfo.getUser().getName());
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "补货单生成成功", "", "");
        } catch (SucessException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "补货单生成成功", e.getMessage(), "");
        } catch (ServiceException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "补货单生成失败", e.getMessage(), "");
        } catch (Exception e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "补货单生成失败", e.getMessage(), "");
        }
    }


    @ApiOperation(value = "确认补货单", response = JSONObject.class, notes = "补货单确认，id:选中的补货单的id")
    @PostMapping(value = "confirmOrder")
    public @ResponseBody
    JSONObject confirmOrder(@RequestBody SetAndModifyModel setModel, HttpSession session) {
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);//用户信息
        List<SysHz> hz = (List) session.getAttribute(BaseSessionInfo.SessionConsignor);
        String hzid = null;
        if (hz.size() > 0) {
            hzid = hz.get(0).getHzid();
        }
        try {
            baseService.confirmOrders(setModel.getId(), userinfo.getUser().getName(),hzid);
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "补货单确认成功", "", "");
        } catch (SucessException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "补货单确认成功", e.getMessage(), "");
        } catch (ServiceException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "补货单确认失败", e.getMessage(), "");
        } catch (Exception e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "补货单确认失败", e.getMessage(), "");
        }
    }


    @ApiOperation(value = "导出人工补货", response = JSONObject.class, notes = "导出人工补货")
    @PostMapping(value = "getOutPutList")
    public JSONObject getOutPutList(HttpServletResponse response, @RequestBody Map map, HttpSession session) throws IOException {
        // map.put("bh",bh);
        //map.put("ids",ids2);
        //Map map = new HashedMap();

        String cjsj_start = (String) map.get("cjsj_start");
        String cjsj_end = (String) map.get("cjsj_end");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String start = null;
        String end = null;
        if (cjsj_start != null && cjsj_start != "") {
            long scsj_start = Long.parseLong(cjsj_start);//开始时间
            start = format.format(new Date(scsj_start));
        }
        if (cjsj_end != null && cjsj_end != "") {
            long scsj_end = Long.parseLong(cjsj_end);//结束时间
            end = format.format(new Date(scsj_end));
        }
        map.put("cjsj_start", start);
        map.put("cjsj_end", end);

        String filename = "补货单导出";
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);//用户信息
        String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库id
        String ckmc = userinfo.getUser().getOrgName();//仓库名称
        map.put("ckid", ckid);
        List<String> ids = (List) map.get("ids");
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("采购订单表", "UTF-8") + ".xls");
        //编码
        response.setCharacterEncoding("UTF-8");
        ExportParams ep = new ExportParams();
        ep.setStyle(ManySheetOneSyler.class);
        List<WmsArtificialReplenishmentDetailed> list = null;
        map.put("ssck", ckmc);

         list = baseService.getOutPutList(ids, map);

        Workbook workbook = ExcelExportUtil.exportExcel(ep, WmsArtificialReplenishment.class, list);
        workbook.write(response.getOutputStream());
        return null;
    }


    @ApiOperation(value = "打印补货单", response = JSONObject.class, notes = "打印补货单,ids:补货单id")
    @PostMapping(value = "print")
    public @ResponseBody
    JSONObject print(@RequestBody SetAndModifyModel setModel) {
        JSONObject jsonObject = null;
        try {
            jsonObject = baseService.print(setModel.getIds());
        } catch (ServiceException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    @GetMapping(value = "getWmsArtificialReplenishment/{id}")
    @ApiOperation(value = "查看单个信息", response = JSONObject.class, notes = "GET查看单个信息")
    public @ResponseBody
    WmsArtificialReplenishment getWmsArtificialReplenishmentById(@PathVariable("id") String id) {
        WmsArtificialReplenishment entity = baseService.baseSelectByPrimaryKey(id);
        return entity;
    }


    @PostMapping(value = "cancelBhd")
    @ApiOperation(value = "取消补货单", response = JSONObject.class, notes = "取消补货单（修改状态，更改为初始）,id:选中的补货单的id")
    public @ResponseBody
    JSONObject cancelBhd(HttpSession session, @RequestBody SetAndModifyModel setModel) {
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        try {
            baseService.cancelBhd(setModel.getId());
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "补货单取消成功", "", "");

        } catch (SucessException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "补货单取消成功", "", "");

        } catch (ServiceException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "补货单取消失败", e.getMessage(), "");

        } catch (Exception e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "补货单取消失败", e.getMessage(), "");

        }

    }


    @ApiOperation(value = "下发补货任务", response = JSONObject.class, notes = "下发补货任务，{\"id\":\"选中的补货单的id\",\"userId\":\"用户id\"，\"userName\":\"用户名\"}")
    @PostMapping(value = "addBhRw")
    public @ResponseBody
    JSONObject addBhRw(@RequestBody Map map, HttpSession session) {
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);//用户信息
        List<SysHz> hz = (List) session.getAttribute(BaseSessionInfo.SessionConsignor);
        String hzid = null;
        if (hz.size() > 0) {
            hzid = hz.get(0).getHzid();
        }
        String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));//仓库id
        try {
            baseService.addBhRw((String)map.get("id"),hzid,(String)map.get("userId"),(String)map.get("userName"),ckid);
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "下发人工补货任务成功", "", "");
        } catch (SucessException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_top.getType(), ReturnType.success.toString(), "下发人工补货任务成功", e.getMessage(), "");
        } catch (ServiceException e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "下发人工补货任务失败", e.getMessage(), "");
        } catch (Exception e) {
            e.printStackTrace();
            return SetStatus.setFunctionType(ReturnType.messageType_right.getType(), ReturnType.error.toString(), "下发人工补货任务失败", e.getMessage(), "");
        }
    }

}
